package com.iye.puretennis.custom;

import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.*;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2015/1/19
 * Time: 10:54
 */
public class CustomGridView extends GridView {

    private View currentView;
    private View dragView;
    private WindowManager windowManager;
    private WindowManager.LayoutParams windowParams;

    private int dragSrcPosition;//开始拖拽项
    private int dragPosition;

    //移动的位置
    private int dragPointX;
    private int dragPointY;
    //当前位置距离边界的位置
    private int dragOffsetX;
    private int dragOffsetY;

    private View targetView;//目标view
    private int dropPosition = -1;//选中项


    private OnDropListener onDropListener;


    public CustomGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setTargetView(View view) {
        targetView = view;
    }

    public void setOnDropListener(OnDropListener onDropListener) {
        this.onDropListener = onDropListener;
    }

    private boolean setOnItemLongClickListener(final MotionEvent ev) {
        this.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           int position, long id) {
                final int x = (int) ev.getX();//触摸点相对于GridView的坐标
                final int y = (int) ev.getY();

                dragSrcPosition = dragPosition = position;

                if (dragPosition == AdapterView.INVALID_POSITION) {
                    return false;
                }

                final ViewGroup item = (ViewGroup) getChildAt(dragPosition - getFirstVisiblePosition());

                currentView = item;

                dragPointX = x - item.getLeft();
                dragPointY = y - item.getTop();

                dragOffsetX = (int) ev.getRawX() - x;
                dragOffsetY = (int) ev.getRawY() - y;

                item.destroyDrawingCache();//清除cache
                item.setDrawingCacheEnabled(true);

                Bitmap bitmap = Bitmap.createBitmap(item.getDrawingCache());
                startDrag(getScaleBitmap(bitmap), x, y);
                return false;
            }
        });

        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            return setOnItemLongClickListener(ev);
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (dragView != null && dragPosition != AdapterView.INVALID_POSITION) {
            int x = (int) ev.getX();
            int y = (int) ev.getY();
            switch (ev.getAction()) {
                case MotionEvent.ACTION_UP:
                    stopDrag();
                    onDrop((int)ev.getRawX(), (int)ev.getRawY());
                    break;

                case MotionEvent.ACTION_MOVE:
                    onDrag(x, y);
                    break;
            }


        }
        return super.onTouchEvent(ev);
    }

    private void startDrag(Bitmap bm, int x, int y) {
        stopDrag();

        windowParams = new WindowManager.LayoutParams();
        windowParams.gravity = Gravity.TOP | Gravity.LEFT;
        //左上角相对于屏幕的坐标
        windowParams.x = x - dragPointX + dragOffsetX;
        windowParams.y = y - dragPointY + dragOffsetY;

        windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        windowParams.format = PixelFormat.TRANSLUCENT;
        windowParams.windowAnimations = 0;

        Context context = this.getContext();
        ImageView imageView = new ImageView(context);
        imageView.setImageBitmap(bm);
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(imageView, windowParams);
        dragView = imageView;
        currentView.setVisibility(INVISIBLE);
    }

    private void stopDrag() {
        if (dragView != null) {
            windowManager.removeView(dragView);
            dragView = null;

        }


    }

    private void onDrag(int x, int y) {
        if (dragView != null) {
            windowParams.alpha = 0.8f;
            windowParams.x = x - dragPointX + dragOffsetX;
            windowParams.y = y - dragPointY + dragOffsetY;
            windowManager.updateViewLayout(dragView, windowParams);
        }

    }

    private void onDrop(int x, int y) {
        boolean inView = isInView(x, y, targetView);
        if (inView) {
            if (onDropListener != null) {
                onDropListener.onDrop(dragSrcPosition);
            }
        } else {
            if (currentView != null) {
                currentView.setVisibility(VISIBLE);
                currentView = null;
            }
        }

    }

    private Bitmap getScaleBitmap(Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postScale(1.1f, 1.1f);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    private boolean isInView(int x, int y, View view) {
        if (view == null) return false;

        int[] location = new int[2];
        view.getLocationInWindow(location);
        int _x = location[0];
        int _y = location[1];
        int width = view.getWidth();
        int height = view.getHeight();

        return _x < x && x < _x + width && _y < y && y < _y + height;
    }

    public interface OnDropListener {
        void onDrop(int dragPosition);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightSpec = heightMeasureSpec;

        if (getLayoutParams().height == LayoutParams.WRAP_CONTENT)
            heightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE, MeasureSpec.AT_MOST);

        super.onMeasure(widthMeasureSpec, heightSpec);
    }
}
